package org.fuys.coder.common.entity;

import org.fuys.coder.common.constants.ResultMessageConstants;
import org.fuys.coder.common.exception.BusinessException;
import org.fuys.coder.domain.substance.model.vo.SubstanceVO;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.PriorityQueue;

/**
 * @projectName: fuys-low-coder
 * @package: org.fuys.coder.common.entity
 * @className: TopK
 * @author: WangJing
 * @description: 更符合项目要求的堆
 * @date: 2024/7/21 10:49
 * @version: 1.0
 */
public class TopK {
    private final int k;
    private final PriorityQueue<SubstanceVO> heap;

    public TopK(int k){
        this.k = k;
        this.heap = new PriorityQueue<>(k);
    }

    public void add(SubstanceVO substanceVO){
        if(heap.size() < k){
            heap.add(substanceVO);
        }else{
            if(ObjectUtils.isEmpty(heap.peek())){
                throw new BusinessException(ResultMessageConstants.ILLEGAL_OPERATION+":热门排行堆顶数据为空");
            }
            //实际上这部分是冗余的判断 在之前已经判断过非空
            if(heap.peek()!=null&&heap.peek().compareTo(substanceVO) < 0){
                heap.poll();
                heap.add(substanceVO);
            }
        }
    }

    public List<SubstanceVO> getK(){
        if(!heap.isEmpty()){
            return new ArrayList<>(heap);
        }
        return null;
    }
}
